package com.app.web.controller.photo;

import com.app.common.annotation.Anonymous;
import com.app.common.core.domain.AjaxResult;
import com.app.common.core.domain.R;
import com.app.common.core.domain.entity.HivisionIDPhotosReq;
import com.app.common.core.domain.entity.HivisionIDPhotosRes;
import com.app.common.core.domain.entity.PhotoDTO;
import com.app.common.core.domain.entity.PhotoVo;
import com.app.common.qny.QiniuKodoUtil;
import com.app.system.service.lSystemPhotoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.PostConstruct;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;

/**
 * @author 徐朴芬
 */
@RestController
@RequestMapping(value = "/photo")
public class Controller {


    private static final Logger log = LoggerFactory.getLogger(Controller.class);

    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;

    @Autowired
    private lSystemPhotoService lSystemPhotoService;

    @Autowired
    private QiniuKodoUtil qiniuKodoUtil;

    @PostConstruct
    public void init() throws IOException {
        ClassPathResource classPathResource = new ClassPathResource("json/idphoto_specs.json");
        try (InputStream inputStream = classPathResource.getInputStream()) {
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
            String json = bufferedReader.lines().collect(java.util.stream.Collectors.joining("\n"));
            redisTemplate.opsForValue().set("photo_specs", json);
            log.debug("redis存入证件照规格成功!");
        }
    }

    /**
     * @return 获取所有证件照规格
     */
    @Anonymous
    @GetMapping(value = "/photoSpecs")
    public AjaxResult photoSpecs() {
        return AjaxResult.success(redisTemplate.opsForValue().get("photo_specs"));
    }


    /**
     * 制作证件照
     *
     * @param photoDTO 证件照参数
     * @return 证件照base地址base64和阿里返回的处理好的证件照地址aliResult
     * @throws IOException 异常
     */
    @PostMapping(value = "/getPhotoSpecs")
    public R<PhotoVo> getPhotoSpecs(@ModelAttribute PhotoDTO photoDTO) throws IOException {
        return R.ok(lSystemPhotoService.getPhotoSpecs(photoDTO));
    }

    /**
     * 调用本地部署服务制作透明背景
     * @param h  证件照生成请求参数实体类，
     * @return 制作结果 base64
     */
    @PostMapping(value = "/getPhotoGetDivisionIDPhotos")
    public R<HivisionIDPhotosRes> getGetDivisionIDPhotos(HivisionIDPhotosReq h) throws Exception {
        HivisionIDPhotosRes res = lSystemPhotoService.GetDivisionIDPhotos(h);
        return res == null? R.fail(): R.ok(res);
    }
}
